<template>
  <el-dialog
    v-model="dialogVisible"
    title="编辑设备信息"
    width="600px"
    :before-close="handleClose"
    class="device-info-dialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      label-position="left"
      class="device-info-form"
    >
      <!-- 设备名称 -->
      <el-form-item label="设备名称" prop="name" class="required-field">
        <el-input
          v-model="formData.name"
          placeholder="请输入设备名称"
          clearable
          size="large"
        />
      </el-form-item>

      <!-- 设备类型 -->
      <el-form-item label="设备类型" prop="deviceType" class="required-field">
        <el-select
          v-model="formData.deviceType"
          placeholder="请选择设备类型"
          style="width: 100%"
          size="large"
          filterable
          allow-create
          default-first-option
          :reserve-keyword="false"
        >
          <el-option
            v-for="type in availableDeviceTypes"
            :key="type.value"
            :label="type.label"
            :value="type.value"
          />
        </el-select>
        <div class="form-tip">
          修改设备类型后，设备将迁移到新的类型分类下
        </div>
      </el-form-item>

      <!-- 当前所属分类 -->
      <!-- <el-form-item label="所属分类">
        <el-tag type="info" size="large">
          {{ getCategoryName(formData.category) }}
        </el-tag>
      </el-form-item> -->
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" size="large">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading" size="large">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
/**
 * 设备信息编辑对话框组件
 * 
 * 功能：
 * - 编辑设备名称
 * - 修改设备类型（修改后自动迁移到新的类型分类下）
 * - 显示设备所属分类
 */

import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { useDeviceStore } from '@/stores/device'

console.log('设备信息对话框组件加载')

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  device: {
    type: Object,
    default: null
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'success'])

// Store
const deviceStore = useDeviceStore()

// 响应式数据
const dialogVisible = ref(false)
const loading = ref(false)
const formRef = ref(null)
const formData = ref({
  id: '',
  name: '',
  deviceType: '',
  category: ''
})

// 分类名称映射
const categoryNames = {
  'emergency_life_support': '急救与生命支持',
  'in_vitro_diagnostics': '体外诊断',
  'infusion_pump': '输注泵',
  'medical_imaging': '医学影像',
  'surgical_equipment': '外科设备'
}

// 获取分类名称
const getCategoryName = (categoryId) => {
  return categoryNames[categoryId] || categoryId
}

// 工具函数：判断设备类型名称是否有效
const isValidDeviceTypeName = (name) => {
  if (!name || typeof name !== 'string') return false
  
  // 过滤掉不合适的设备类型名
  const invalidNames = [
    'N系列', 'ePM系列', 'R12心电图机', 'mWear系列',
    'D3系列', 'D6系列', 'AED专题',
    'BS360E系列', 'BS480系列', 'CL1000i系列', 'CL900i系列',
    '深科输液泵系列', 'BeneFusion输液泵系列',
    'DC40系列', 'M9系列', 'DigiEye680系列', 'DigiEye280系列',
    'HyLED X系列', 'HyLED C系列', 'HyBase3000', 'UniBase30',
    'DC-40', 'DC-60', 'DC-80'
  ]
  
  if (invalidNames.includes(name)) return false
  
  // 检查是否包含不合适的关键词
  const invalidKeywords = ['系列', '专题', 'Pro', 'Plus', 'Max']
  for (const keyword of invalidKeywords) {
    if (name.includes(keyword)) {
      return false
    }
  }
  
  // 检查是否为纯数字或纯字母缩写
  if (/^\d+$/.test(name) || /^[A-Z]{2,}\d*$/.test(name)) {
    return false
  }
  
  return true
}

// 可用的设备类型列表
const availableDeviceTypes = computed(() => {
  const existingTypes = new Set()
  
  deviceStore.devices.forEach(device => {
    if (device.type === 'category' && device.isCategory === true) {
      if (device.name && isValidDeviceTypeName(device.name)) {
        existingTypes.add(device.name)
      }
    }
  })
  
  // 添加常见的设备类型作为默认选项
  const defaultTypes = [
    '监护仪',
    '除颤仪',
    '输液泵',
    '超声设备',
    '检验设备',
    '手术设备'
  ]
  
  defaultTypes.forEach(type => existingTypes.add(type))
  
  const typeArray = Array.from(existingTypes).sort()
  
  return typeArray.map(type => ({
    label: type,
    value: type
  }))
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
    { min: 2, max: 50, message: '设备名称长度在2到50个字符', trigger: 'blur' }
  ],
  deviceType: [
    { required: true, message: '请选择设备类型', trigger: 'change' }
  ]
}

// 初始化表单数据
const initFormData = () => {
  if (props.device) {
    console.log('初始化设备信息:', props.device)
    
    // 查找设备的父级设备类型
    let deviceType = ''
    if (props.device.parentId) {
      // 如果有parentId，说明是子设备，需要找到父设备
      const parentDevice = deviceStore.devices.find(d => d.id === props.device.parentId)
      if (parentDevice) {
        deviceType = parentDevice.name
      }
    }
    
    formData.value = {
      id: props.device.id || '',
      name: props.device.name || '',
      deviceType: deviceType || '',
      category: props.device.category || ''
    }
    
    console.log('表单数据初始化完成:', formData.value)
  }
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    // 表单验证
    await formRef.value.validate()
    
    loading.value = true
    
    console.log('=== 开始更新设备信息 ===')
    console.log('设备ID:', formData.value.id)
    console.log('新的设备名称:', formData.value.name)
    console.log('新的设备类型:', formData.value.deviceType)
    
    // 调用store的更新方法
    await deviceStore.updateDeviceInfo(
      formData.value.id,
      formData.value.name,
      formData.value.deviceType,
      formData.value.category
    )
    
    ElMessage.success('设备信息更新成功')
    
    // 触发成功事件
    emit('success')
    
    // 关闭对话框
    handleClose()
    
  } catch (error) {
    if (error?.message) {
      console.error('更新设备信息失败:', error)
      ElMessage.error('更新失败：' + error.message)
    } else {
      console.log('表单验证失败')
    }
  } finally {
    loading.value = false
  }
}

// 处理关闭
const handleClose = () => {
  dialogVisible.value = false
  emit('update:modelValue', false)
  
  // 重置表单
  nextTick(() => {
    formRef.value?.resetFields()
  })
}

// 监听props变化
watch(() => props.modelValue, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    initFormData()
  }
})

watch(() => dialogVisible.value, (newVal) => {
  if (!newVal) {
    emit('update:modelValue', false)
  }
})
</script>

<style scoped>
.device-info-dialog {
  border-radius: 8px;
}

.device-info-form {
  padding: 20px 0;
}

.required-field :deep(.el-form-item__label)::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.form-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-dialog__header) {
  padding: 20px 24px;
  border-bottom: 1px solid #e4e7ed;
  margin-right: 0;
}

:deep(.el-dialog__body) {
  padding: 20px 24px;
}

:deep(.el-dialog__footer) {
  padding: 20px 24px;
  border-top: 1px solid #e4e7ed;
}

:deep(.el-form-item) {
  margin-bottom: 24px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #262626;
}

:deep(.el-input__inner),
:deep(.el-textarea__inner),
:deep(.el-select) {
  border-radius: 4px;
}

:deep(.el-tag) {
  padding: 8px 16px;
  font-size: 14px;
}
</style>


